// 引用：Web实现悬浮球-可点击&拖拽&禁止区域https://blog.csdn.net/qq_44859233/article/details/134698121

const initball = function () {
  const ballDom = document.getElementById("ballBtn");
  let isDragging = false;
  let bindDomProfile = null;
  let containerProfile = null;
  const mousedownPos = {
    x: 0,
    y: 0,
  };
  const ballMove = (event) => {
    console.log("mousemove");
    isDragging = true;
    const moveArrangeX = containerProfile.right - bindDomProfile.width; // 元素可在x 轴移动的最大值
    const moveArrangeY = containerProfile.bottom - bindDomProfile.height; // 元素可在y 轴移动的最大值
    const clientX =
      (event.touches && event.touches[0] && event.touches[0].clientX) ||
      event.clientX;
    const clientY =
      (event.touches && event.touches[0] && event.touches[0].clientY) ||
      event.clientY;

    const moveXDiff = clientX - mousedownPos.x; // 鼠标在x 轴移动的距离
    const moveYDiff = clientY - mousedownPos.y; // 鼠标在y 轴移动的距离
    let canMoveX = Math.max(
      0,
      Math.min(bindDomProfile.left + moveXDiff, moveArrangeX)
    );
    let canMoveY = Math.max(
      0,
      Math.min(bindDomProfile.top + moveYDiff, moveArrangeY)
    );

    ballDom.style.transform = `translate3d(0px, ${canMoveY}px, 0)`;
    ballDom.style.pointerEvents = "none";
  };

  const ballUp = (event) => {
    // 移除鼠标移动事件
    window.removeEventListener("mousemove", ballMove);
    window.removeEventListener("touchmove", ballMove);
    // 移除鼠标松开事件
    window.removeEventListener("mouseup", ballUp);
    window.removeEventListener("touchend", ballUp);
    ballDom.style.pointerEvents = null;
  };

  const ballMoveDown = (event) => {
    isDragging = false;
    bindDomProfile = ballDom.getBoundingClientRect();
    mousedownPos.x =
      (event.touches && event.touches[0].clientX) || event.clientX;
    mousedownPos.y =
      (event.touches && event.touches[0].clientY) || event.clientY;

    window.addEventListener("mousemove", ballMove, false);
    window.addEventListener("mouseup", ballUp, false);
    window.addEventListener("touchmove", ballMove, false);
    window.addEventListener("touchend", ballUp, false);
  };

  window.onload = () => {
    // 移动的范围
    containerProfile = {
      bottom: window.innerHeight,
      left: 0,
      right: window.innerWidth,
      top: 0,
    };

    ballDom.addEventListener("mousedown", ballMoveDown);
    ballDom.addEventListener("touchstart", ballMoveDown);
  };
};
